<?php

namespace App\Http\Controllers;

use App\Models\Comment;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CommentController extends Controller
{
    public function store(Request $request, Post $post)
    {
        $request->validate([
            'content' => 'required|min:3|max:1000',
            'parent_id' => 'nullable|exists:comments,id',
        ]);

        $comment = $post->comments()->create([
            'user_id' => Auth::id(),
            'parent_id' => $request->parent_id,
            'content' => $request->content,
            'status' => Auth::check() ? 'approved' : 'pending',
            'author_name' => Auth::check() ? null : $request->author_name,
            'author_email' => Auth::check() ? null : $request->author_email,
            'author_ip' => $request->ip(),
        ]);

        return back()->with('message', '评论已提交' . (!Auth::check() ? '，等待审核' : ''));
    }

    public function destroy(Comment $comment)
    {
        // 只有评论作者或管理员可以删除评论
        if (Auth::id() !== $comment->user_id && !Auth::user()->isAdmin()) {
            abort(403, '无权限删除此评论');
        }

        $comment->delete();

        return back()->with('message', '评论已删除');
    }
}